package com.adou.p2p.controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.adou.p2p.model.UserValue;
import com.adou.p2p.service.UserService;

@Controller
public class LoginController {
	@Autowired
	private UserService userService;
	
	@PostMapping("login")
	public ModelAndView  login(HttpServletRequest request, HttpServletResponse response) {
		ModelAndView view = new ModelAndView();
		// 1.得到username,password
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		UserValue userValue = userService.findByUsernameAndPassword(username, password);
		
		if(userValue != null) {
			// 登录成功
			request.getSession().setAttribute("user", userValue);
			view.setViewName("home");
		} else {
			view.addObject("loginError","登录失败");
			view.setViewName("redirect:/login.jsp");
		}
		return view;
	}
	
	/**
	 * 推出
	 * @param request
	 * @param response
	 */
	@PostMapping("shutdown")
	public void shutdown(HttpServletRequest request, HttpServletResponse response) {
		// 销毁session
		request.getSession().invalidate();
	}
	
}
